package com.example.db.utils;

import android.database.sqlite.SQLiteDatabase;

import net.tsz.afinal.FinalDb;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by kkmike999 on 16/2/12.
 */
public class DbHelper {

    public static void beginTransaction(FinalDb finalDb) {
        try {
            SQLiteDatabase db = getDatabase(finalDb);

            Method beginTranMethod = SQLiteDatabase.class.getDeclaredMethod("beginTransaction");
            beginTranMethod.invoke(db);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void endTransaction(FinalDb finalDb) {
        try {
            SQLiteDatabase db = getDatabase(finalDb);

            Method setSuccessMethod = SQLiteDatabase.class.getDeclaredMethod("setTransactionSuccessful");
            Method endTranMethod = SQLiteDatabase.class.getDeclaredMethod("endTransaction");

            setSuccessMethod.setAccessible(true);
            endTranMethod.setAccessible(true);
            setSuccessMethod.invoke(db);
            endTranMethod.invoke(db);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SQLiteDatabase getDatabase(FinalDb finalDb) {
        try {
            Field dbField = FinalDb.class.getDeclaredField("db");
            dbField.setAccessible(true);

            SQLiteDatabase db = (SQLiteDatabase) dbField.get(finalDb);

            return db;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
